﻿using Common.Communal;
using ERP.Domain.Workorders.Inventory;
using MediatR;
using Product.API.Read.Applications.Commands.WorkOrder.Inventory;
using SqlSugar;

namespace Product.API.Read.Applications.CommandHandlers.WorkOrder.Inventory
{
    /// <summary>
    /// 库存汇总显示命令处理
    /// </summary>
    public class WarehouseShowCommandHandler : IRequestHandler<WarehouseShowCommand, ApiResult<ApiPaging<Warehouse>>>
    {
        /// <summary>
        /// SqlSugar
        /// </summary>
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">SqlSugar</param>
        public WarehouseShowCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public Task<ApiResult<ApiPaging<Warehouse>>> Handle(WarehouseShowCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<Warehouse>> result = new ApiResult<ApiPaging<Warehouse>>();
            result.Code = EnumCode.Ok;
            result.Message = EnumCode.Ok.ToString();

            var outDataList = db.Queryable<InventoryTransactionWordOrder>()
            .Where(x => x.TransactionFlag == 0
                     && x.TransactionTime >= request.StartTime
                     && x.TransactionTime <= request.EndTime)
            .GroupBy(x => x.WarehouseName)
            .Select(g => new
            {
                outWarehouseName = g.WarehouseName,
                OutboundCount = g.InboundQuantity
            }).ToList();

            var intoDataList = db.Queryable<InventoryTransactionWordOrder>()
                .Where(x => x.TransactionFlag == 1
                && x.TransactionTime >= request.StartTime
                && x.TransactionTime <= request.EndTime)
                .GroupBy(x => x.WarehouseName)
                .Select(g => new
                {
                    intoWarehouseName = g.WarehouseName,
                    IntoboundCount = g.InboundQuantity
                }).ToList();

            int totalPage = 0;
            int totalCount = 0;
            var data = db.Queryable<Warehouse>().ToPageList(request.pageIndex, request.pageSize, ref totalCount, ref totalPage);
            ApiPaging<Warehouse> page = new ApiPaging<Warehouse>();
            page.TotalCount = totalCount;
            page.TotalPage = totalPage;
            page.Data = data;
            result.Data = page;

            return Task.FromResult(result);
        }
    }
}
